package com.excalibur.core.security;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.excalibur.core.util.HexUtil;

/**
 * @author tianbenzhen@pwrd.com
 * @version 2014-3-18 下午5:59:00
 */
public class RSAKeyUtils {

	public static final String PUBLIC_KEY = "RSAPublicKey";
	public static final String PRIVATE_KEY = "RSAPrivateKey";

	public static final int HEX = 0;
	public static final int BASE64 = 1;

	/**
	 * 生产密钥对
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> initKey() throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		keyPairGen.initialize(1024, new SecureRandom());
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		Map<String, String> keyMap = new HashMap<String, String>();
		keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
		keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
		return keyMap;
	}

	/**
	 * 生产密钥对
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> initKey(int encodeMode) throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		keyPairGen.initialize(1024, new SecureRandom());
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		Map<String, String> keyMap = new HashMap<String, String>();
		String privateKeyString = null;
		String publicKeyString = null;
		if (encodeMode == HEX) {
			privateKeyString = HexUtil.toHexString(privateKey.getEncoded());
			publicKeyString = HexUtil.toHexString(publicKey.getEncoded());
		} else {
			privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
			publicKeyString = Base64.encodeBase64String(publicKey.getEncoded());
		}
		keyMap.put(PUBLIC_KEY, publicKeyString);
		keyMap.put(PRIVATE_KEY, privateKeyString);
		return keyMap;
	}

	/**
	 * 从字符串中加载公钥
	 * 
	 * @param publicKeyStr
	 * @return
	 * @throws Exception
	 */
	public static RSAPublicKey loadRSAPublicKey(String publicKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decodeBase64(publicKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法", e);
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法", e);
		}
	}

	/**
	 * 从字符串中加载公钥
	 * 
	 * @param publicKeyStr
	 * @param encodeMode
	 * @return
	 * @throws Exception
	 */
	public static RSAPublicKey loadRSAPublicKey(String publicKeyStr, int encodeMode) throws Exception {
		try {
			byte[] buffer = null;
			if (encodeMode == HEX) {
				buffer = HexUtil.toByteArray(publicKeyStr);
			} else {
				buffer = Base64.decodeBase64(publicKeyStr);
			}
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法", e);
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法", e);
		}
	}

	/**
	 * 从字符串中加载私钥
	 * 
	 * @param privateKeyStr
	 * @return
	 * @throws Exception
	 */
	public static RSAPrivateKey loadRSAPrivateKey(String privateKeyStr) throws Exception {
		try {
			byte[] buffer = Base64.decodeBase64(privateKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法", e);
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法", e);
		}
	}

	/**
	 * 从字符串中加载私钥
	 * 
	 * @param privateKeyStr
	 * @param encodeMode
	 * @return
	 * @throws Exception
	 */
	public static RSAPrivateKey loadRSAPrivateKey(String privateKeyStr, int encodeMode) throws Exception {
		try {
			byte[] buffer = null;
			if (encodeMode == HEX) {
				buffer = HexUtil.toByteArray(privateKeyStr);
			} else {
				buffer = Base64.decodeBase64(privateKeyStr);
			}
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
			return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法", e);
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法", e);
		}
	}

}
